# coding=UTF-8
from datetime import date, datetime


class ModelFieldParse(object):
    '''
    model字段转换
    '''
    field_type_dict = {}

    def to_html_obj(self, field_type, val):
        tranfer = self.field_type_dict.get(field_type, None)
        if tranfer:
            func = getattr(self, tranfer['tranfer_func'], '')
            config = tranfer.get('config', '')
            if func:
                val = func(val, config)
        return val

    def _to_datetime_str(self, val, config):
        if val:
            val = val.strftime(config)
        return val

    def _to_datetime(self, val, config):
        return val

    def _to_date_str(self, val, config):
        if val:
            val = val.strftime(config)
        return val

    def _to_date(self, val, config):
        return val

    def _to_int(self, val, config):
        return val



class DjangoModelFieldParse(ModelFieldParse):
    '''
    根据model的field类型自动转换查询数据
    '''
    field_type_dict = {
        datetime: {
            'tranfer_func': '_to_datetime_str',  # 转换函数
            'config': '%Y-%m-%d %H:%M:%S'  # 转换时默认使用的配置参数
        },
        date: {
            'tranfer_func': '_to_date_str',  # 转换函数
            'config': '%Y-%m-%d'  # 转换时默认使用的配置参数
        }
    }

class RequestParamParse(object):
    '''
    针对Django的model请求参数解析
    '''
    # 默认针对数据直接使用 __in 后缀，一下符号已证明可用，使用示例：{'~key': name}
    symbol_dict = {
        '~': '__startswith',
        '!*': '__icontains',
        '*': '__contains',
        '>-': '__gte',
        '>': '__gt',
        '<-': '__lte',
        '<': '__lt'
    }

    def parse_param_dict(self, source_param_dict, fields_dict):
        param_dict = {}
        keys = fields_dict.keys()
        for key, value in source_param_dict.items():
            if value in ['', None]:
                continue
            # 处理参数
            key, after = self._parse_param(key, value, keys)
            if key:
                # 转换数据类型
                field_class = fields_dict.get(key, None)
                key, value = self._column_auto_transfer(key, after, value, field_class)
                if key and value not in ['', None]:
                    param_dict.update({
                        key: value
                    })
        return param_dict

    def _parse_param(self, param_key, param_val, field_list):
        '''
        将key解析成django的orm参数形式
        :param param_key: 参数key
        :param param_val: 参数key的值
        :param field_list: 字段列表
        :return: 
        '''
        key, after = None, ''
        if param_key not in field_list:
            for symbol, val in self.symbol_dict.items():
                flag, temp_key, temp_after = self._anaylize_key(param_key, symbol, val, field_list)
                if flag:
                    key, after = temp_key, temp_after
                    break
        else:
            key = param_key
        if not after and key and isinstance(param_val, list):
            after = '__in'
        return key, after

    def _anaylize_key(self, key, symbol, symbol_val, field_list):
        '''
        分析参数的key，并将key解析
        :param key:参数key 
        :param symbol: 分析的符号
        :param symbol_val: 符号对应的后缀
        :param field_list: 
        :return: 
        '''
        flag = False
        after = ''
        temp_key_list = key.split(symbol)
        temp_key_list_len = len(temp_key_list)
        if temp_key_list_len == 2 and temp_key_list[0] == '':
            if temp_key_list[1] in field_list:
                flag = True
                key = temp_key_list[1]
                after = symbol_val
        return flag, key, after

    def _column_auto_transfer(self, key, after, value, field_class):
        '''
        自动将参数中的所有model中的字段转成对应的类型
        :param key: 参数key
        :param after: 参数key的后缀
        :param value: 参数key的值
        :param field_class: model中字段的类型
        :return: 
        '''
        key = '%s%s' % (key, after) if after else key
        if field_class:
            if isinstance(value, list):
                result = []
                for val in value:
                    temp = field_class.to_python(val)
                    result.append(temp)
            else:
                result = field_class.to_python(value)
            value = result
        return key, value

class Null:
    '''
    空
    '''
    name = 'null'
